#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <syslog.h>
#include <errno.h>
#define MAXFILE 65535

int main(void)
{
    pid_t child,child1,child2,sid;
    int i,fd,len;
    char *buf = "This is a Dameon\n";
    len = strlen(buf);

    child1 = fork();//The first step
    if(child1 < 0)
    {
        printf("error fork\n"); 
        exit (1);
    }
    else if(child1 > 0)
    {
      printf("parent end...\n"); 
      exit (0);
    }
    printf("child start...\n"); 
    //打开系统日至服务,openlog
    openlog("demo_update", LOG_PID, LOG_DAEMON);
    printf("after openlog\n"); 
    if((sid = setsid()) < 0)
    {
           syslog(LOG_ERR, "%s\n", "setsid");        
      exit(1);
    }
    printf("errno=%d sid=%d\n",errno,sid);

    printf("after setsid\n"); 
    if((sid = chdir("/")) < 0)
    {
        syslog(LOG_ERR, "%s\n", "chdir");        
        exit(1);
    }
    printf("after chdir\n");
 
    umask(0);
    printf("after umask\n");
    for(i = 0; i < MAXFILE; i++)
        close(i);
    printf("after close\n");

    child2 = fork();
    if(child2 == -1)
    {
        perror("child2 fork error"); 
        exit(1);
    }
    else if(child2 == 0)
    {
        syslog(LOG_ERR, "child2 will exit in 10 seconds"); 
        sleep(10);
        syslog(LOG_ERR, "child2 exit now"); 
        exit(0);
    }
    else
    {
      do
      {
          child = waitpid(child2, NULL, WNOHANG);
          if(child == 0)
          {
            printf("child2 has not exit\n"); 
            syslog(LOG_ERR, "child2 has not exit");
            sleep(1);
          }
      }while(child == 0);
      closelog();
      while(1)
      {
        sleep(5); 
        syslog(LOG_ERR, "sleep forever");
      }

    }

    //It is complete to create dameon,the code below will work in dameon
      //Open the log file of daemon,and write it to the log record of open
        if((fd = open("/tmp/dameon.log", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) 
        {
            syslog(LOG_ERR, "open error"); 
            exit(1);
        }
       printf("after open\n");
        write(fd, buf, len+1);
        close(fd);
        sleep(2);
       printf("after while\n");
    closelog();
    exit(0);
}
